from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.views.generic import ListView, CreateView, UpdateView, DetailView
from .models import Ticket

class MyTicketListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
    model = Ticket
    template_name = 'tickets/my_ticket_list.html'
    permission_required = 'tickets.can_view_own_ticket'

    def get_queryset(self):
        # 返回登录用户自己的工单
        return Ticket.objects.filter(created_by=self.request.user)

class CreateTicketView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
    model = Ticket
    fields = ['title', 'description', 'priority']
    template_name = 'tickets/ticket_form.html'
    permission_required = 'tickets.can_submit_ticket'

    def form_valid(self, form):
        form.instance.creator = self.request.user  # 设置创建人为当前用户
        return super().form_valid(form)

class EditTicketView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
    model = Ticket
    fields = ['title', 'description', 'priority', 'status']
    template_name = 'tickets/ticket_form.html'
    permission_required = 'tickets.can_submit_ticket'

    def get_queryset(self):
        # 只允许编辑自己的工单
        return Ticket.objects.filter(creator=self.request.user)
